package com.cuitrip.business.comment;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import com.cuitrip.apiservice.OrderBusiness;
import com.cuitrip.apiservice.model.ApiManager;
import com.cuitrip.business.comment.model.Comment;
import com.cuitrip.business.comment.model.Number;
import com.cuitrip.business.comment.ui.NumberHolderView;
import com.cuitrip.business.order.model.OrderItem;
import com.cuitrip.component.emoji.NPSEmojiView;
import com.cuitrip.component.seek.VerticalSeekBar;
import com.cuitrip.service.R;
import com.lab.adapter.HolderViewAdapter;
import com.lab.app.customui.CustomUiConfig;
import com.lab.app.customui.CustomUiFragmentActivity;
import com.lab.component.list.LinearListView;
import com.lab.jumper.Jumper;
import com.lab.network.model.CtApiResponse;
import com.lab.network.model.IProxyCallback;
import com.lab.network.model.ProxyResult;
import com.lab.network.proxy.ApiProxy;
import com.lab.utils.DisplayUtil;
import com.lab.utils.ToastUtil;
import com.lab.utils.Utils;
import com.pnikosis.materialishprogress.ProgressWheel;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * NPS 打分界面
 * Created on 7/26.
 */
public class NPSRateActivity extends CustomUiFragmentActivity implements IProxyCallback, View.OnTouchListener {


    public static final String NPS_SCORE = "NPSRateActivity.NPS_Score";
    private static final int INITIAL_VALUE = 5;

    public static final String COMMENT_KEY = "comment_key";
    public static final int REQUEST_CODE = 0x01;

    @Bind(R.id.submit)
    View submit;

    @Bind(R.id.nps_text)
    TextView npsText;
    @Bind(R.id.num_list)
    LinearListView numList;
    @Bind(R.id.vol_seek_bar)
    VerticalSeekBar volSeekBar;

    public static final int HAPPY_RATE = 9;
    public static final int SOSO_RATE = 7;
    @Bind(R.id.nps_emoji_view)
    NPSEmojiView npsEmojiView;
    @Bind(R.id.seek_ball)
    ImageView seekBall;
    @Bind(R.id.progress_text)
    TextView progressText;
    @Bind(R.id.progress_wheel)
    ProgressWheel progressWheel;
    @Bind(R.id.submit_text)
    TextView submitText;

    private Comment comment;

    private ApiProxy mApiProxy = new ApiProxy(this);


    private HolderViewAdapter mAdapter;

    private List<Number> mNumberList = new ArrayList<Number>();
    private int mNpsScore;
    private int lastX;
    private int lastY;
    private int[] randomScore={0,10};

    protected void onCreate(Bundle savedInstanceState) {
        Intent intent = getIntent();
        if (intent.hasExtra(COMMENT_KEY)) {
            comment = (Comment) intent.getSerializableExtra(COMMENT_KEY);
        }
        super.onCreate(savedInstanceState, R.layout.nps_page);
    }

    @Override
    public void initView() {
        ButterKnife.bind(this);
        initNumberData();
        mAdapter = new HolderViewAdapter(this, mNumberList, NumberHolderView.class);
        numList.setAdapter(mAdapter);
    }


    @Override
    public void initData() {
        int index=(new Random().nextInt(2));
        mNpsScore =randomScore[index];

        volSeekBar.setProgressAndThumb(mNpsScore);
        updateProgressText(mNpsScore);
    }

    private void initNumberData() {
        for (int i = 10; i >= 0; i--) {
            Number number = new Number(i);
            mNumberList.add(number);
        }
    }

    private void updateSeekBall(int progress) {
        LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) seekBall.getLayoutParams();

        int bottomBetween = DisplayUtil.dip2px(0.f);
        if (progress > 0) {
            bottomBetween += progress * DisplayUtil.dip2px(38.5f);
        }


        layoutParams.setMargins(layoutParams.leftMargin, layoutParams.topMargin, layoutParams.rightMargin, bottomBetween);
        seekBall.setLayoutParams(layoutParams);
    }

    private void updateProgressText(int progress) {
        progressText.setText(String.valueOf(progress));
    }

    @Override
    public void initListener() {
        seekBall.setOnTouchListener(this);

        volSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (progress >= HAPPY_RATE) {
                    npsEmojiView.setEmotionRate(NPSEmojiView.EmotionRate.Happy);
                } else if (progress >= SOSO_RATE) {
                    npsEmojiView.setEmotionRate(NPSEmojiView.EmotionRate.SoSo);
                } else {
                    npsEmojiView.setEmotionRate(NPSEmojiView.EmotionRate.Pity);
                }

                updateSeekBall(progress);
                updateProgressText(progress);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });
    }

    @OnClick(R.id.submit)
    void submitInput() {
        progressStart();
        mNpsScore = volSeekBar.getProgress();
        OrderBusiness.submitNPS(mApiProxy, mNpsScore, "1", "");
    }

    private void progressStart() {
        submitText.setVisibility(View.INVISIBLE);
        progressWheel.setVisibility(View.VISIBLE);
    }

    private void progressEnd() {
        submitText.setVisibility(View.VISIBLE);
        progressWheel.setVisibility(View.INVISIBLE);
    }

    @Override
    public boolean initCloseTopBar() {
        return false;
    }

    @Override
    public void onTopbarLeftPress() {
        finish();
    }

    @Override
    public CustomUiConfig initCustomUiConfig() {
        CustomUiConfig customUiConfig = new CustomUiConfig();
        customUiConfig.mTopbarLeftAreaName = getString(R.string.back_icon);
        customUiConfig.mTopbarMiddleAreaName = getString(R.string.review_and_feedback);
        return customUiConfig;

    }

    private void handleNPSResult(CtApiResponse response) {
        if (response.isResponseNormal()) {
            OrderBusiness.submitReview(mApiProxy, comment.getOrderId(), comment.getRating(), comment.getText());
        } else {
            if (!TextUtils.isEmpty(response.msg)) {
                ToastUtil.toast(response.msg);
            }
            progressEnd();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            setResult(RESULT_OK);
            finish();
        }
    }

    private void handleCommentResult(CtApiResponse response) {
        progressEnd();
        if (response.isResponseNormal()) {
            sendBroadcast(
                    new Intent(OrderItem.ORDER_STATUS_CHANGED_ACTION));
            if (mNpsScore >= 0 && mNpsScore < 7) {
                Intent intent = new Intent(this, FeedBackActivity.class);
                intent.putExtra(COMMENT_KEY, comment);
                intent.putExtra(NPS_SCORE, mNpsScore);
                //跳转用户反馈界面
                Jumper.launchActivityForResult(this, intent, REQUEST_CODE);
            } else if (mNpsScore >= 7 && mNpsScore <= 10) {
                //跳转评价成功页面
                Intent intent = new Intent(NPSRateActivity.this, CommentSuccessActivity.class).putExtra(COMMENT_KEY, comment);
                Jumper.launchActivityForResult(this, intent, REQUEST_CODE);
            }
            setResult(RESULT_OK);
            finish();
        } else {
            if (!TextUtils.isEmpty(response.msg)) {
                ToastUtil.toast(response.msg);
            }
        }
    }

    @Override
    public boolean onProxyResult(ProxyResult<?> result) {
        CtApiResponse response = (CtApiResponse) result.getData();
        if (ApiManager.SUBMIT_NPS_INFO.equals(response.getApiName())) {
            handleNPSResult(response);
        } else if (ApiManager.SUBMIT_COMMENT.equals(response.getApiName())) {
            handleCommentResult(response);
        }
        return false;
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        final int i;
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                lastX = (int) event.getRawX();
                lastY = (int) event.getRawY();
                break;
            case MotionEvent.ACTION_MOVE:
                int dy = (int) event.getRawY() - lastY;

                int top = v.getTop() + dy;
                int bottom = v.getBottom() + dy;
                // 设置不能出界
                if (top < 0) {
                    top = 0;
                    bottom = top + v.getHeight();
                }

                if (bottom > Utils.dp2pixel(440)) {
                    bottom = Utils.dp2pixel(440);
                    top = bottom - v.getHeight();
                }
                v.layout(v.getLeft(), top, v.getRight(), bottom);
                lastX = (int) event.getRawX();
                lastY = (int) event.getRawY();
                i = volSeekBar.calcProgress(event.getRawY() - Utils.dp2pixel(140));
                volSeekBar.setProgress(i);
                break;
            case MotionEvent.ACTION_UP:
                i = volSeekBar.calcProgress(event.getRawY() - Utils.dp2pixel(140));
                volSeekBar.setProgress(i);
                break;
        }
        return true;
    }

}
